package com.vhly.appspot;

import com.vhly.appspot.util.StreamUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-3-25
 * Time: 16:24:07
 */
public class HttpClient {
    public static ResponseData request(String url, byte[] post, Hashtable<String, String> addHeaders) {
        ResponseData rd = null;
        if (url != null) {
            String method = post != null && post.length > 0 ? "POST" : "GET";
            URL u = null;
            HttpURLConnection http = null;
            ByteArrayOutputStream bout = null;
            try {
                u = new URL(url);
                http = (HttpURLConnection) u.openConnection();
                http.setRequestMethod(method);
                http.setDoInput(true);
                if (addHeaders != null && !addHeaders.isEmpty()) {
                    Enumeration<String> keys = addHeaders.keys();
                    String k, v;
                    while (keys.hasMoreElements()) {
                        k = keys.nextElement();
                        v = addHeaders.get(k);
                        http.setRequestProperty(k, v);
                    }
                }
                if (method.equals("POST")) {
                    http.setRequestProperty("Content-Length", Integer.toString(post.length));
                    http.setDoOutput(true);
                    OutputStream out = http.getOutputStream();
                    out.write(post);
                    out.close();
                }
                int responseCode = http.getResponseCode();
                rd = new ResponseData();
                rd.stateCode = responseCode;
                rd.contentEncoding = http.getContentEncoding();
                int iv = http.getContentLength();
                rd.contentLength = iv;
                rd.contentType = http.getContentType();
                InputStream in = http.getInputStream();
                if (iv > 0) {
                    rd.data = new byte[iv];
                    in.read(rd.data);
                } else {
                    bout = new ByteArrayOutputStream();
                    StreamUtil.writeStream(in, bout);
                    rd.data = bout.toByteArray();
                }
            } catch (IOException ioe) {

            } finally {
                StreamUtil.close(bout);
                StreamUtil.close(http);
            }
        }
        return rd;
    }
}
